﻿using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Helper;
using CleanArchitecture.Infrastructure.Entities.Settings;
using CleanArchitecture.Infrastructure.Models;
using FluentValidation;
using System.Text.RegularExpressions;

namespace CleanArchitecture.Web.Validators.AdminUsers
{
    public partial class LoginValidator : BaseModelValidator<LoginModel>
    {
        public LoginValidator(AdminUserSettings adminuserSettings, SecuritySettings securitySettings)
        {
            RuleFor(x => x.LoginUser).IsLoginUsername(adminuserSettings).When(x =>
            {
                bool valideLoginname = securitySettings.AdminUserLogin.Contains(AdminUserLoginType.Loginname.ToString("F"))
                                    && !CommonHelper.IsValidEmail(x.LoginUser) && !CommonHelper.IsValidMobile(x.LoginUser);
               //当数据库未指定后台用户登录方式时，提供默认用户登录方式
                if(securitySettings.AdminUserLogin == null || securitySettings.AdminUserLogin.Count == 0)
                    return true;
                else if (valideLoginname) return true;
                else return false;                    
            });
            RuleFor(x => x.LoginUser).EmailAddress().When(x =>
            {
                //只要登录信息中有@符号, 以邮箱方式校验登录信息
                bool validateEmail = securitySettings.AdminUserLogin.Contains(AdminUserLoginType.Email.ToString("F"))
                                   && x.LoginUser.IndexOf('@', System.StringComparison.CurrentCultureIgnoreCase) >= 0;
                if (securitySettings.AdminUserLogin != null && validateEmail)
                    return true;
                return false;
            }).WithMessage(ValidatorRuleString.EmailNotValid);
            RuleFor(x => x.LoginUser).IsValidMobile().When(x =>
            {
                //用户登录名要求以字母开头
                //只要登录信息以数字开头, 以手机方式校验登录信息
                bool validateMobile = securitySettings.AdminUserLogin.Contains(AdminUserLoginType.Mobile.ToString("F"))
                                   && Regex.IsMatch(x.LoginUser, @"^\d+");
                if (securitySettings.AdminUserLogin != null && validateMobile)
                    return true;
                return false;
            }).WithMessage(ValidatorRuleString.MobileNumNotValid);
            int passwordminLen = adminuserSettings.PasswordMinLength ?? 6;
            RuleFor(x => x.Password).IsLoginPasswordCorrect(passwordminLen);
        }
    }
}